<template class="a">
  <div>
    <img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
    <img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
		<img src="/image/bjt.jpg" alt="">
    </div>
      
</template>

<script>
  export default {
    
  }
  var imgs = document.querySelectorAll('img')
		// offsetTop是元素与offsetParent的距离，循环获取直到页面顶部
		function getTop(el) {
			var top = el.offsetTop
			while (el = el.offsetParent) {
				top += el.offsetTop
			}
			return top
		}

		function lazyLoad(imgs) {
			// 获取可视区域高度
			var height = document.documentElement.clientHeight
			var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
			for (var i = 0; i < imgs.length; i++) {
				// 获取元素大小及相对视口的位置
				var bound = imgs[i].getBoundingClientRect()
				if (bound.top > height) {
					// 移除已添加的class样式,下次重新上滑的时候重新赋值才会还能出现上移效果
					imgs[i].removeAttribute('class')
				}

				if (height + scrollTop > getTop(imgs[i])) {
					// 给图片属性src赋值
					imgs[i].src = imgs[i].getAttribute('src')
					// 给图片元素添加写有上移效果的class类名
					imgs[i].classList.add('transform_img')
				}
			}
		}

		// 在页面加载和onscroll()在滚动条滚动的时候触发
		window.onload = window.onscroll = function() {
			lazyLoad(imgs)
		}
</script>

<style lang="scss" scoped>
*{
				padding: 0;
				margin: 0;
			}
			body{
				padding: 40px 20px 0;
			}
			img {
				display: block;
				width: 100%;
				height: 300px;
				margin-bottom: 20px;
				transition: 1s;
			}
			.transform_img{
				transform: translateY(-20px);
				transition: 1s;
			}
      .a{
        position:fixed;
        left:0;
        top:0;
      }
		</style>
